package com.sjgtw.cloud.system.controller;

import com.sjgtw.cloud.common.core.constant.UserConstants;
import com.sjgtw.cloud.common.core.domain.R;
import com.sjgtw.cloud.common.core.exception.BaseException;
import com.sjgtw.cloud.common.core.utils.SecurityUtils;
import com.sjgtw.cloud.common.core.utils.poi.ExcelUtil;
import com.sjgtw.cloud.common.core.web.controller.BaseController;
import com.sjgtw.cloud.common.core.web.domain.AjaxResult;
import com.sjgtw.cloud.common.core.web.page.TableDataInfo;
import com.sjgtw.cloud.common.log.annotation.Log;
import com.sjgtw.cloud.common.log.enums.BusinessType;
import com.sjgtw.cloud.common.security.annotation.PreAuthorize;
import com.sjgtw.cloud.system.api.domain.SysDept;
import com.sjgtw.cloud.system.api.domain.SysRole;
import com.sjgtw.cloud.system.api.domain.SysUser;
import com.sjgtw.cloud.system.domain.SysUserRole;
import com.sjgtw.cloud.system.service.ISysDeptService;
import com.sjgtw.cloud.system.service.ISysRoleService;
import com.sjgtw.cloud.system.service.ISysUserService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * <p>Title: 角色信息管理</p>
 * <p>Description: </p>
 * @author Admin
 * @date 2020-7-7
 */
@Api(value = "角色信息管理",tags = {"角色信息管理接口"}) 
@RestController
@RequestMapping("/role")
public class SysRoleController extends BaseController
{
    @Autowired
    private ISysRoleService roleService;
    
    @Autowired
    private ISysDeptService deptService;
    
    @Autowired
    private ISysUserService userService;
    
    /**
     * <p>Title: 获取角色列表--分页</p>
     * <p>Description: </p>
     * @param role
     * @return
     */
    @ApiOperation("获取角色列表-分页")
    @PreAuthorize(hasPermi = "system:role:list")
    @GetMapping("/list")
    public TableDataInfo list(SysRole role)
    {
        startPage();
        List<SysRole> list = roleService.selectRoleList(role);
        return getDataTable(list);
    }
    
    /**
     * <p>Title: 角色数据导出</p>
     * <p>Description: </p>
     * @param response
     * @param role
     * @throws IOException
     */
    @Log(title = "角色管理", businessType = BusinessType.EXPORT)
    @PreAuthorize(hasPermi = "system:role:export")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysRole role) throws IOException
    {
//        List<SysRole> list = roleService.selectRoleList(role);
//        ExcelUtil<SysRole> util = new ExcelUtil<SysRole>(SysRole.class);
//        util.exportExcel(response, list, "角色数据");
    	throw new BaseException("角色数据为敏感数据，不提供数据导出功能！");
    }

    /**
     * <p>Title: 根据角色ID获取信息</p>
     * <p>Description: </p>
     * @param roleId
     * @return
     */
    @ApiOperation("根据角色ID获取信息")
   	@ApiImplicitParam(name = "roleId", value = "角色ID", required = true, dataType = "Long", paramType = "path")
    @PreAuthorize(hasPermi = "system:role:query")
    @GetMapping(value = "/{roleId}")
    public AjaxResult getInfo(@PathVariable Long roleId)
    {
        return AjaxResult.success(roleService.selectRoleById(roleId));
    }

    /**
     * <p>Title: 新增角色</p>
     * <p>Description: </p>
     * @param role
     * @return
     */
    @ApiOperation("新增角色")
    @PreAuthorize(hasPermi = "system:role:add")
    @Log(title = "角色管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysRole role)
    {
        if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleNameUnique(role)))
        {
            return AjaxResult.error("新增角色'" + role.getRoleName() + "'失败，角色名称已存在！");
        }
        else if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleKeyUnique(role)))
        {
            return AjaxResult.error("新增角色'" + role.getRoleName() + "'失败，角色权限已存在！");
        }
        role.setCreateBy(SecurityUtils.getUsername());
        return toAjax(roleService.insertRole(role));

    }

    /**
     * <p>Title: 修改角色</p>
     * <p>Description: </p>
     * @param role
     * @return
     */
    @ApiOperation("修改角色")
    @PreAuthorize(hasPermi = "system:role:edit")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysRole role)
    {
        roleService.checkRoleAllowed(role);
        if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleNameUnique(role)))
        {
            return AjaxResult.error("修改角色'" + role.getRoleName() + "'失败，角色名称已存在！");
        }
        else if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleKeyUnique(role)))
        {
            return AjaxResult.error("修改角色'" + role.getRoleName() + "'失败，角色权限已存在！");
        }
        role.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(roleService.updateRole(role));
    }

    /**
     * <p>Title: 修改角色对应的数据权限</p>
     * <p>Description: </p>
     * @param role
     * @return
     */
    @ApiOperation("修改角色对应的数据权限")
    @PreAuthorize(hasPermi = "system:role:edit")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PutMapping("/dataScope")
    public AjaxResult dataScope(@RequestBody SysRole role)
    {
        roleService.checkRoleAllowed(role);
        return toAjax(roleService.authDataScope(role));
    }

    /**
     * <p>Title: 修改角色状态</p>
     * <p>Description: </p>
     * @param role
     * @return
     */
    @ApiOperation("修改角色状态")
    @PreAuthorize(hasPermi = "system:role:edit")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody SysRole role)
    {
        roleService.checkRoleAllowed(role);
        role.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(roleService.updateRoleStatus(role));
    }

    /**
     * <p>Title: 删除角色</p>
     * <p>Description: </p>
     * @param roleIds
     * @return
     */
    @ApiOperation("删除角色")
    @ApiImplicitParam(name = "roleIds", value = "角色ID数组集", required = true, allowMultiple=true , dataType = "Long", paramType = "path")
    @PreAuthorize(hasPermi = "system:role:remove")
    @Log(title = "角色管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{roleIds}")
    public AjaxResult remove(@PathVariable Long[] roleIds)
    {
        return toAjax(roleService.deleteRoleByIds(roleIds));
    }

    /**
     * <p>Title: 获取角色选择框列表</p>
     * <p>Description: </p>
     * @return
     */
    @ApiOperation("获取角色选择框列表")
    @PreAuthorize(hasPermi = "system:role:query")
    @GetMapping("/optionselect")
    public AjaxResult optionselect()
    {
        return AjaxResult.success(roleService.selectRoleAll());
    }
    
    /**
     * <p>Title: 已分配用户角色列表</p>
     * <p>Description: </p>
     * @return
     */
    @PreAuthorize(hasPermi = "system:role:list")
    @GetMapping("/authUser/allocatedList")
    public TableDataInfo allocatedList(SysUser user)
    {
        startPage();
        List<SysUser> list = userService.selectAllocatedList(user);
        return getDataTable(list);
    }
    
    /**
     * <p>Title: 未分配用户角色列表</p>
     * <p>Description: </p>
     * @return
     */
    @PreAuthorize(hasPermi = "system:role:list")
    @GetMapping("/authUser/unallocatedList")
    public TableDataInfo unallocatedList(SysUser user)
    {
        startPage();
        List<SysUser> list = userService.selectUnallocatedList(user);
        return getDataTable(list);
    }
    
    /**
	 * <p>Title: 加载对应角色部门列表树</p>
	 * <p>Description: </p>
	 * @param roleId
	 * @return
	 */
	@ApiOperation("加载对应角色部门列表树")
    @PreAuthorize(hasPermi = "system:role:query")
    @GetMapping(value = "/deptTree/{roleId}")
    public AjaxResult deptTree(@PathVariable("roleId") Long roleId)
    {
        List<SysDept> depts = deptService.selectDeptList(new SysDept());
        AjaxResult ajax = AjaxResult.success();
        ajax.put("checkedKeys", deptService.selectDeptListByRoleId(roleId));
        ajax.put("depts", deptService.buildDeptTreeSelect(depts));
        return ajax;
    }
	
	/**
	 * <p>Title: 批量选择用户</p>
	 * <p>Description: 批量添加操作R-U</p>
	 * @param roleId
	 * @param userIds
	 * @return
	 */
	@PreAuthorize(hasPermi = "system:role:edit")
    @Log(title = "角色管理", businessType = BusinessType.GRANT)
    @PutMapping("/authUser/selectAll")
    public AjaxResult selectAuthUserAll(Long roleId, Long[] userIds)
    {
        roleService.checkRoleDataScope(roleId);
        return toAjax(roleService.insertAuthUsers(roleId, userIds));
    }
	
	/**
	 * <p>Title: 取消授权用户</p>
	 * <p>Description: 单体取消操作R-U</p>
	 * @param userRole
	 * @return
	 */
	@PreAuthorize(hasPermi = "system:role:edit")
    @Log(title = "角色管理", businessType = BusinessType.GRANT)
    @PutMapping("/authUser/cancel")
    public AjaxResult cancelAuthUser(@RequestBody SysUserRole userRole)
    {
        return toAjax(roleService.deleteAuthUser(userRole));
    }

    /**
     * <p>Title: 批量取消授权用户</p>
     * <p>Description: 批量取消操作R-U</p>
     * @param roleId
     * @param userIds
     * @return
     */
	@PreAuthorize(hasPermi = "system:role:edit")
    @Log(title = "角色管理", businessType = BusinessType.GRANT)
    @PutMapping("/authUser/cancelAll")
    public AjaxResult cancelAuthUserAll(Long roleId, Long[] userIds)
    {
        return toAjax(roleService.deleteAuthUsers(roleId, userIds));
    }
    
    /**
	 * <p>Title: 通过角色roleKey查询角色</p>
	 * <p>Description: </p>
	 * @param roleKey 角色权限
	 * @return 角色信息
	 */
    @GetMapping("/findrole/{roleKey}")
    public R<SysRole> findRoleByRoleKey(@PathVariable("roleKey") String roleKey)
    {
    	SysRole sysRole = roleService.selectRoleByRoleKey(roleKey);
        return R.ok(sysRole);
    }
}